import axios from 'axios'
let token = '';
axios.defaults.withCredentials = false;
axios.defaults.headers.common['token'] = token;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';//配置请求头
// http request拦截器 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    let token = window.localStorage.getItem("token")
    if (token) {
        //将token放到请求头发送给服务器,将tokenkey放在请求头中
        config.headers.token = token;
        //也可以这种写法
        // config.headers['token'] = token;
    }
    return config;
}, function (error) {
    console.log('请求超时');
    // Do something with request error
    return Promise.reject(error);
});
// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    if (response.data && response.data.code) {
        if (response.data.message === 'token失效' || response.data.message === '请求头中没有token') {
            //未登录 
            //todo需要跳转到登录
            console.log("登录信息已失效，请重新登录");
        }
        if (parseInt(response.data.code) === -1) {
            console.log("请求失败");
        }
    }
    return response;
}, function (error) {
    console.log("服务器连接失败");
    return Promise.reject(error);
})
let base = '';
//通用方法
export const POST = (url:string, params:object) => {
    const getTimestamp = new Date().getTime();
    return axios.post(`${base}${url}?timer=${getTimestamp}`, params).then(res => res.data)
}
export const GET = (url:string, params:object) => {
    const getTimestamp = new Date().getTime();
    return axios.get(`${base}${url}?timer=${getTimestamp}`, { params: params }).then(res => res.data)
}
export const PUT = (url:string, params:object) => {
    return axios.put(`${base}${url}`, params).then(res => res.data)
}
export const DELETE = (url:string, params:object) => {
    return axios.delete(`${base}${url}`, { params: params }).then(res => res.data)
}
export const PATCH = (url:string, params:object) => {
    return axios.patch(`${base}${url}`, params).then(res => res.data)
}
/**
 ************************
 * 使用规范
 * postRequest是挂载的全局变量POST,getRequest是挂载的全局变量GET
 * 在main.js中处理
   import {POST,GET} from './tools/axios.ts';
   const app=createApp(App);
   app.config.globalProperties.postRequest=POST;
   app.config.globalProperties.getRequest=GET;
 * post请求  this.postRequest(url,param).then(res => {})
 * get请求  this.getRequest(url,param).then(res => {})
 ***********************
 */

